# @Time : 2024/10/31 21:16
# @Author : Fioman 
# @Phone : 13149920693
"""
pickling: 将python对象转换为字节流(即将对象序列化)的过程.这个字节流可以保存到文件中或者通过网络传输
unpickling: 将字节流恢复为原来的Python对象(即反序列化)的过程
使用场景:
将 Python 对象保存到文件中，以便以后重新加载。
在网络传输中，将 Python 对象发送到远程机器。
在进程间通信中共享 Python 对象。
"""
import pickle

data = {
    "name": "Fioman",
    "age": 30,
    "gender": "Male",
}
with open('fioman.pkl', 'wb') as f:
    pickle.dump(data, f)
print("Data has been pickled and  saved  to 'data.pkl' file")

with open('fioman.pkl', 'rb') as f:
    data = pickle.load(f)
print("Data has been unpickled and data is {}".format(data))

"""
有时候,我们不想直接处理文件,而是希望处理内存中的字节流,可以使用pickle.dumps()和 pickle.loads()
"""
data = {
    "name": "Fioman",
    "age": 30,
    "gender": "Male",
}
serializedData = pickle.dumps(data)
print("serializedData = {}".format(serializedData))
deserializedData = pickle.loads(serializedData)
print("deserializedData = {}".format(deserializedData))
